package fms.core;

import fms.util.CRCaculation;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by adcc on 2016/6/21.
 */
public class Msg620Builder {

    public static int MASNum=0;
    public static SimpleDateFormat sdf=new SimpleDateFormat("ddmmss");
    public static String build( String aircraftID,
                      String freeTextOfUpMsg, String replySMI,String uplinksender,String uplinkreceiver,String snavailable){
        StringBuilder sb=new StringBuilder();
        sb.append((char) 1 + "QU " + uplinkreceiver+"\r\n");
        sb.append("."+uplinksender+" "+sdf.format(new Date())+"\r\n");
        sb.append((char)2+replySMI+"\r\n");
        sb.append("AN "+aircraftID+"/"+"MA "+generateFormatMas()+"I\r\n");
        String crc="";

        if(snavailable.equals("yes")){
            String sn=Long.toString(new Date().getTime());
            sn=sn.substring(sn.length() - 10);
            int length=freeTextOfUpMsg.length();
//            freeTextOfUpMsg=freeTextOfUpMsg.substring(0,length-4)+"/SN"+sn;
            freeTextOfUpMsg=freeTextOfUpMsg+"/SN"+sn;
        }

        try {
            crc= CRCaculation.CRCaculation(freeTextOfUpMsg);
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if(crc.equals("")){
            return "";
        }
        else{
            freeTextOfUpMsg=freeTextOfUpMsg+crc;
            return sb.append("-  "+freeTextOfUpMsg+(char)3).toString();
        }

    }

    public static String generateFormatMas(){

        String result="";

        if(MASNum==999){
            MASNum=1;
        }
        else{
            MASNum++;
        }
        if(MASNum>=0&&MASNum<10){
            result="00"+MASNum;
        }
        else if(MASNum>=10&&MASNum<100){
            result="0"+MASNum;
        }
        else{
            result=Integer.toString(MASNum);
        }
        return result;
    }
}
